<?php 

require_once('oauth_coin.inc.php');

function get_opensocial_data()
{
	// check if the request is correctly signed
	$signature_valid = validate_coin_oauth($_GET,$_POST,file_get_contents('php://input'));
	if (!$signature_valid) { throw new Exception("Invalid oauth signature"); }
	//error_log("OAuth signature is valid");

	// read body of POST request
	$input_raw = file_get_contents('php://input');

	// parse the incoming JSON and put it in an associative array
	$input = array();
	$input_decoded = json_decode($input_raw, true);
	if ($input_decoded===null) $input_decoded = array();
	foreach( $input_decoded as $k=>$v)
	{
		// iGoogle and Shindig using different keys in the JSON encoding
		// handle both here
		if (array_key_exists('data', $v))
		{
			$input[ $v['id'] ] = $v['data'];
		}
		elseif (array_key_exists('result', $v))
		{
			$input[ $v['id'] ] = $v['result'];
		}
	}

	// parse GET
	foreach( $_GET as $k=>$v )
	{
		$input[ $k ] = $v;
	}

	// write data to a file for debugging
	if (1)
	{
		$fd = fopen("/tmp/opensocial.txt", "w");
		fwrite($fd, $input_raw);
		fwrite($fd, "\n\n");
		#fwrite($fd, print_r($input_decoded,true));
		#fwrite($fd, "\n\n");
		fwrite($fd, print_r($input,true));
		fclose($fd);
	}

	return $input;
}

function osdata2json($osdata)
{
	$result = array();
	foreach ($osdata as $key => $arr)
	{
		$result[] = array( "id" => $key, "result" => $arr );
	}
	return json_encode($result,true);
}
